package com.vhall.component.service.guosen.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.room.ExternalLiveStatsMapper;
import com.vhall.component.entity.room.entity.ExternalLiveStatsEntity;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.service.guosen.ExternalLiveStatsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * ExternalLiveStatsServiceImpl-
 *
 * @author xing.wang
 * @date 2023/12/19
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ExternalLiveStatsServiceImpl extends ServiceImpl<ExternalLiveStatsMapper, ExternalLiveStatsEntity>
        implements ExternalLiveStatsService {
    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 获取直播间外部观看数据次数
     *
     * @param ilId 房间id
     * @return
     */
    @Override
    public Integer getCacheLiveExternalChannelViewCount(Integer ilId) {
        Integer externalChannelViewCount = 0;
        String key = RedisKey.CACHE_LIVE_EXTERNAL_CHANNEL_VIEW_COUNT + ilId;
        if (redisTemplate.hasKey(key)) {
            String cacheValue = redisTemplate.opsForValue().get(key);
            if (NumberUtil.isNumber(cacheValue)) {
                externalChannelViewCount = Integer.valueOf(cacheValue);
            }
        }else{
            if (Objects.nonNull(ilId) && ilId != 0) {
                LambdaQueryWrapper<ExternalLiveStatsEntity> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(ExternalLiveStatsEntity::getIlId, ilId).last(" limit 1 ");
                ExternalLiveStatsEntity externalLiveStatsEntity = getOne(queryWrapper);
                externalChannelViewCount = Optional.ofNullable(Optional.ofNullable(externalLiveStatsEntity).orElse(new ExternalLiveStatsEntity()).getExternalChannelViewCount()).orElse(0);
            }
            redisTemplate.opsForValue().set(key,String.valueOf(externalChannelViewCount),2, TimeUnit.MINUTES);
        }
        return externalChannelViewCount;
    }
}
